#![feature(proc_macro_hygiene, decl_macro)]

use rocket::config::{Config, Environment};
use rocket::http::{ContentType, Status};
use rocket::{get, post, routes};
use rocket::{Data, Response, State};

extern crate clipboard;

use clipboard::ClipboardContext;
use clipboard::ClipboardProvider;

use std::fs::File;
use std::io::prelude::Read;
use std::io::Cursor;
use std::sync::{Arc, Mutex};

fn main() {
    let ctx = Arc::new(Mutex::new(ClipboardContext::new().unwrap()));

    let index_html = read_file("index.html");

    let config = Config::build(Environment::Development)
        .address("0.0.0.0")
        .finalize()
        .unwrap();

    rocket::custom(config)
        .manage(ctx)
        .manage(index_html)
        .mount("/", routes![index, paste])
        .launch();
}

// 获取主页
#[get("/")]
fn index(content_state: State<String>) -> Result<Response<'static>, Status> {
    Response::build()
        .header(ContentType::HTML)
        .sized_body(Cursor::new(content_state.clone()))
        .ok()
}

// 写入剪贴板
#[post("/paste", data = "<content>")]
fn paste(content: Data, ctx_state: State<Arc<Mutex<ClipboardContext>>>) -> &'static str {
    let mut paste_string = String::new();
    content.open().read_to_string(&mut paste_string).unwrap();

    let mut ctx = ctx_state.lock().unwrap();
    ctx.set_contents(paste_string).unwrap();

    "ok"
}

// 读取文件
fn read_file(filename: &str) -> String {
    let mut file = File::open(filename).unwrap();
    let mut contents = String::new();

    file.read_to_string(&mut contents).unwrap();

    contents
}
